package com.breaker.kata.leetcode;

import com.breaker.kata.leetcode.domain.ListNode;

public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int num = (l1.val + l2.val) / 10;
        return new ListNode((l1.val + l2.val) % 10, createNextNode(l1.next, l2.next, num));
    }

    private ListNode createNextNode(ListNode l1, ListNode l2, int num) {
        if (l1 == null && l2 != null) {
            int val = l2.val + num;
            return new ListNode(val % 10, createNextNode(null, l2.next, val / 10));
        }
        if (l2 == null && l1 != null) {
            int val = l1.val + num;
            return new ListNode(val % 10, createNextNode(null, l1.next, val / 10));
        }
        if (l1 != null) {
            int val = l1.val + l2.val + num;
            return new ListNode(val % 10, createNextNode(l1.next, l2.next, val / 10));
        }
        if (num == 0) {
            return null;
        }
        return new ListNode(num);
    }
}

